package com.nio;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @Author 咕唧
 * @Date 2022/7/5 19:38
 * @Version 1.0
 * nio序列化操作
 */
public class Nio02 {
    public static void main(String[] args) throws Exception {
        //创建一个存放数据的buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(30);

//        ByteBuffer buffer = byteBuffer.put("这是一个测试文件".getBytes(StandardCharsets.UTF_8));
//
//        //写入一个文件
//        FileOutputStream fileOutputStream = new FileOutputStream("aa.txt");
//        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();
//        //翻转一下，在写入
//        buffer.flip();
//        int write = fileOutputStreamChannel.write(buffer);


        //创建一个文件流
        FileInputStream fileInputStream = new FileInputStream("aa.txt");
        //转成nio的方式进行操作,channel可以将数据存放或者从buffer读取出来
        FileChannel channel = fileInputStream.getChannel();

        //声明一个char通道，用来解决中文编码问题的
        CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
        //声明一个charBuffer转换读取出来的中文
        CharBuffer charBuffer = CharBuffer.allocate(30);

        //将数据读取到buffer里面
        //返回-1代表读完了，
        while (channel.read(byteBuffer) != -1) {
            //翻转
            byteBuffer.flip();
            decoder.decode(byteBuffer, charBuffer, true);
            charBuffer.flip();
            while (charBuffer.hasRemaining()) {
                System.out.print(charBuffer.get());
            }
            //byteBuffer.compact();// 压缩：把未读过的内容保留，已读过的内容清理掉
            //charBuffer.clear();
            byteBuffer.clear();
        }
        System.out.println();
        //翻转，恢复初始状态，还可以重新读或者写
        charBuffer.flip();
        while (charBuffer.hasRemaining()) {
            System.out.print(charBuffer.get());
        }
        System.out.println();
        System.out.println("下面是一个只读的通道数据");
        CharBuffer readOnlyBuffer = charBuffer.asReadOnlyBuffer();
        readOnlyBuffer.flip();
        while (readOnlyBuffer.hasRemaining()) {
            System.out.print(readOnlyBuffer.get());
        }

        fileInputStream.close();

    }
}
